
<?php

if(!isset($_GET['fileSel'])) {
  $fileno = 1;
  $annotator1 = $annotator2 = 1;
} else {
  $fileno = $_GET['fileSel'];
  $annotator1 = $_GET['annotator1Sel'];
  $annotator2 = $_GET['annotator2Sel'];
}

$params = "filenumber=$fileno&annotator1=$annotator1&annotator2=$annotator2";

$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";

$database = "ThreadExtraction";
$dataTable = "Data";
$annotationsTable = "Annotations";
$fileTable = "Files";


$db = mysql_connect($dbhost, $dbuser, $dbpassword) or die("Connection Error: " . mysql_error());
mysql_select_db($database) or die("Error conecting to db.");

$filesToAnnotatorsSql = "select filenumber, annotator from data, annotations where data.id=postId group by filenumber,annotator";
$filesToAnnotators = mysql_query($filesToAnnotatorsSql) or die("Couldn't execute file query." . mysql_error());
$fileMap = array();
$file = array();
$no = 0;
while($row = mysql_fetch_array($filesToAnnotators, MYSQL_ASSOC)) {
  $no = $row["filenumber"];
  if(!isset($fileMap[$no])) {
	$fileMap[$no] = array();
  }
  array_push($fileMap[$no], $row["annotator"]); 
}

$filesSql = "select id, name from files where id in (" . implode(",", array_keys($fileMap)) . ")";
$files = mysql_query($filesSql) or die("Couldn't execute file query." . mysql_error());
while($row = mysql_fetch_array($files, MYSQL_ASSOC)) {
  $file[] = array("name" => $row["name"], "id" => $row["id"], "annotators" => $fileMap[$row["id"]]);
}

$fileJSON =  json_encode($file);

$script .= "var fileMap = $fileJSON;\n";

$dataSql = "select threada, threadb, common from threadcomparison where filenumber = $fileno and annotatora = $annotator1 and annotatorb = $annotator2";
$data = mysql_query($dataSql) or die("Couldn't execute data query.". mysql_error());

$i=0;
$script .= "var commonPosts = new Array();\n";
while($row = mysql_fetch_array($data, MYSQL_ASSOC)) {
        $threada = $row["threada"];
	$threadb = $row["threadb"];
	$common = $row["common"];
	$convertIdQuery = "select group_concat(postnum) as ids from data where id in ($common)";
	$convertId = mysql_query($convertIdQuery) or die("Couldn't execute data query.") . mysql_error();
	$idRow = mysql_fetch_array($convertId, MYSQL_ASSOC);
	$common = "[" . preg_replace('/(\d+)/', '"$1"', $idRow["ids"]) . "]";
	if(!isset($ts[$threada])) {
		$ts[$threada] = Array();
		$script .= "commonPosts[$threada] = new Array();\n";
	}
	if(!isset($ts[$threada][$threadb])) {
		$ts[$threada][$threadb] = 1;
		$script .= "commonPosts[$threada][$threadb] = new Array();\n";
	}
        $script .= "commonPosts[$threada][$threadb]=$common;\n";
}


?>


<html>
<head>
<link rel="stylesheet" type="text/css" media="screen" href="css/sunny/jquery-ui-1.7.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/custom.css" />

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.sprintf.js"></script>
<script type="text/javascript" src="js/dropdown.js"></script>

<script type="text/javascript">
<?php echo $script; ?>
</script>

<script type="text/javascript"> 
        var lastsel;
	var lastsela;
	var lastselb;
        var filenumber;
        var postWidth = 40;
	var timestampWidth = 70;
	var userWidth = 90;
	var threadWidth = postWidth;
	var relationWidth = threadWidth;

	var threada;
	var threadb;
	var curPosts;

	var mainHeight = 400;
	var threadHeight = 200;

        var primaryDd = '#fileSel';
	var annotator1Dd = '#annotator1Sel';
	var annotator2Dd = '#annotator2Sel';

	jQuery().ready(function (){ 

populateSelect($(primaryDd).get(0), $.map(fileMap, function(f) { return { name: f.name, value: f.id} }));
$(primaryDd).val(<?php echo $fileno?>);
$(primaryDd).bind('change', function() {
	var file = this.value;
	populateSelect($(annotator1Dd).get(0), $.map(fileMap[file]["annotators"], function(ann) { return {name: ann, value: ann}}));
	populateSelect($(annotator2Dd).get(0), $.map(fileMap[file]["annotators"], function(ann) { return {name: ann, value: ann}}));
  });

jQuery("#list1").jqGrid({ 
	url:'./event_handlers/getMainJQGridDataExamine.php?<?php echo $params;?>', 
	datatype: "json", 
	colNames:['Post ID','Timestamp', 'Sys', 'User', 'Content','Parent','Relation','Thread', 'Parent2', 'Relation2', 'Thread2'],
	 colModel:[ 
		{name:'ID',index:'postnum', width:postWidth,}, 
		{name:'Time',index:'timestamp', width:timestampWidth},
		{name:'Sys',index:'system', width:1},
		{name:'User',index:'user', width:userWidth}, 
		{name:'Content',index:'content', width:500, formatter:colorThread}, 
		{name:'Parent',index:'parent', width:postWidth, editable:true, edittype:'text'}, 
		{name:'Relation',index:'relation', width:relationWidth,align:"right", editable:true, edittype:'text'}, 
		{name:'Thread',index:'thread', width:threadWidth}, 
		{name:'Parent2',index:'parent', width:postWidth, editable:true, edittype:'text'}, 
		{name:'Relation2',index:'relation', width:relationWidth,align:"right", editable:true, edittype:'text'}, 
		{name:'Thread2',index:'thread', width:threadWidth,} ], 

	onSelectRow: function(id){
		var linea, lineb;
		var posa, posb;
		var graphHeight;
      		if(id && id!==lastsel){
        		jQuery('#list1').restoreRow(lastsel);
//        		jQuery('#list1').editRow(id,true);
                        threada = jQuery('#list1').jqGrid('getCell', id, 'Thread');
                        threadb = jQuery('#list1').jqGrid('getCell', id, 'Thread2');
			curPosts = commonPosts[threada][threadb];
			filenumber = jQuery('#list1').getUserDataItem('fileno');
			urla = $.sprintf("getThread.php?file=%d&thread=%d&annotator=%d", filenumber, threada, 1);
			urlb = $.sprintf("getThread.php?file=%d&thread=%d&annotator=%d", filenumber, threadb, 2);

			linea = $.sprintf("#%s-%s", id, 1);
			lineb = $.sprintf("#%s-%s", id, 2);

          		lastsel=id;

			jQuery('#annotator1').setGridParam({url:urla}).trigger("reloadGrid");
			jQuery('#annotator2').setGridParam({url:urlb}).trigger("reloadGrid");
                        graphHeight = jQuery('#annotator1').getGridParam('height');
//			alert(jQuery(linea).position()['top']);
                        jQuery('#gbox_annotator1 .ui-jqgrid-bdiv').scrollTop(jQuery(linea).position()['top'] - graphHeight/2);
                        graphHeight = jQuery('#annotator2').getGridParam('height');
                        jQuery('#gbox_annotator1 .ui-jqgrid-bdiv').scrollTop(jQuery(lineb).position()['top'] - graphHeight/2);
      		}
    	},
        afterInsertRow: function(id)  {
             if(jQuery('#list1').jqGrid('getCell', id, 'Sys') == 1) {
                jQuery('#list1').jqGrid('setRowData', id, 'false', "system");
             }
        },
        jsonreader: {
		userdata: "userdata",
	},
	height: mainHeight,
	rowNum: -1,
        scrollOffset: 20,
        sortable: true,
	pager: jQuery('#pager1'), 
	sortname: 'id', 
	viewrecords: true,
	sortorder: "desc",
	caption:"Example", 
 	loadonce:true,
}).navGrid('#pager1',{add:false,del:false}); 

jQuery("#annotator1").jqGrid({
        url:'getThread.php?file=1&thread=1&annotator=1',
        datatype: "json",
colNames:['Post ID','Timestamp', 'User', 'Content','Parent','Relation'],
         colModel:[  
                {name:'Post ID',index:'postnum', width:postWidth,}, 
                {name:'Timestamp',index:'timestamp', width:timestampWidth},
                {name:'User',index:'user', width:userWidth},
                {name:'Content',index:'content', width:300, formatter:colorThread, classes:"contentThread"},
                {name:'Parent',index:'parent', width:postWidth, editable:true, edittype:'text'},
                {name:'Relation',index:'relation', width:relationWidth,align:"right", editable:true, edittype:'text'},
		],
        onSelectRow: function(idv){
		var id = idv.split("-")[0];
                if(id && id!==lastsela){
                        jQuery('#annotator1').restoreRow(lastsel);
//                      jQuery('#annotator1').editRow(id,true);
			var graphHeight = jQuery('#list1').getGridParam('height');
			var rowTop = jQuery('#list1 #'+id).position()['top'] - graphHeight/2;
			jQuery('#gbox_list1 .ui-jqgrid-bdiv').scrollTop(rowTop);

                        lastsel=idv;
                }
        },
	afterInsertRow: function(idv)  {
		if(!(curPosts === undefined)) {
			var id = idv.split("-")[0];
             		if(jQuery.inArray(id, curPosts) > -1) {
				if(id == lastsel) {
                                        jQuery('#annotator1').jqGrid('setRowData', idv, 'false', "selected");
;
                                } 
			} else {
                                        jQuery('#annotator1').jqGrid('setRowData', idv, 'false', "highlight");
                        }
		}
        },
        height: threadHeight,
        rowNum: -1,
        scrollOffset: 20,
        sortable: true,
        sortname: 'id',
        viewrecords: true,
        sortorder: "desc",
        caption:"Annotator 1",
});

jQuery("#annotator2").jqGrid({
        url:'getThread.php?file=1&thread=1&annotator=2',
        datatype: "json",
colNames:['Post ID','Timestamp', 'User', 'Content','Parent','Relation'],
         colModel:[
                {name:'Post ID',index:'postnum', width:postWidth,},
                {name:'Timestamp',index:'timestamp', width:timestampWidth},
                {name:'User',index:'user', width:userWidth},
                {name:'Content',index:'content', width:300, formatter:colorThread, classes:"contentThread"},
                {name:'Parent',index:'parent', width:postWidth, editable:true, edittype:'text'},
                {name:'Relation',index:'relation', width:relationWidth,align:"right", editable:true, edittype:'text'},
                ],
        onSelectRow: function(idv){
                var id = idv.split("-")[0];
                if(id && id!==lastsela){
                        jQuery('#annotator2').restoreRow(lastsel);
//                      jQuery('#annotator2').editRow(id,true);
                        var graphHeight = jQuery('#list1').getGridParam('height');
                        var rowTop = jQuery('#list1 #'+id).position()['top'] - graphHeight/2;
                        jQuery('#gbox_list1 .ui-jqgrid-bdiv').scrollTop(rowTop);

                        lastsel=idv;
                }
        },
        afterInsertRow: function(idv)  {
                if(!(curPosts === undefined)) {
                        var id = idv.split("-")[0];
                        if(jQuery.inArray(id, curPosts) > -1) {
				if(id == lastsel) {
					jQuery('#annotator2').jqGrid('setRowData', idv, 'false', "selected");
					var graphHeight = jQuery('#annotator2').getGridParam('height');
//		                        var rowTop = jQuery('idv).position()['top'] - graphHeight/2;
//		                        jQuery('#gbox_annotator2 .ui-jqgrid-bdiv').scrollTop(rowTop);
				}
			} else {
                                	jQuery('#annotator2').jqGrid('setRowData', idv, 'false', "highlight");
				}
                }
        },
        height: threadHeight,
        rowNum: -1,
        scrollOffset: 20,
        sortable: true,
        sortname: 'id',
        viewrecords: true,
        sortorder: "desc",
        caption:"Annotator 2",
});


  function colorThread(cell, options, rowArr) {
//     if(rowArr[2] == 1) {
//     }
       return cell;
  }
});
</script>
</head>

<body>

<form id="selector" name="selector" action="examineFile.php" method="get">
	<select name="fileSel" id="fileSel"></select>
	<select name="annotator1Sel" id="annotator1Sel"></select>
	<select name="annotator2Sel" id="annotator2Sel"></select>
	<INPUT type="submit" value="Send"> <INPUT type="reset">
</form>

<table id="list1"></table> <div id="pager1"></div>

<table id="container">
<tr>
<td><table id="annotator1"></table></td>

<td><table id="annotator2"></table></td>
</tr>
</table>
</body>
</html> 
